<template>
  <div id="employee-main-container" class="dingtalk-index">
    <xr-header
      style="padding: 0px 15px 15px 0;"
      ft-top="0"
      icon-class="wk wk-schedule"
      icon-color="#2362FB"
      placeholder="请输入员工姓名"
      show-search
      search-icon-type="icon"
      @search="searchClick" >
      <template slot="ft">
        <el-date-picker
          v-model="month"
          :picker-options="pickerOptions"
          :clearable="false"
          style="width: 200px;margin-right: 15px;"
          type="month"
          format="yyyy-MM"
          value-format="yyyy-MM"
          placeholder="选择月份"
          @change="refreshList"/>
        <el-select v-model="deptName" placeholder="选择部门" filterable clearable @change="refreshList">
          <el-option v-for="(item, index) in deptNameList" :key="index" :value="item">{{ item }}</el-option>
        </el-select>
        <el-button style="margin-left: 20px;" type="primary" @click="exportExcel">导出表格</el-button>
      </template>
    </xr-header>
    <div class="title">
      <h2>韩味{{ month.replace('-', '年') }}月考勤统计</h2>
      <!-- <a @click="generator">重新生成</a> -->
      <el-button v-if="refreshData.showRefresh" :disabled="refreshData.refreshDisabled" type="text" size="mini" @click="refreshList">{{ refreshData.refreshText }}</el-button>
      <el-button v-else type="text" size="mini" @click="generator">重新生成</el-button>
    </div>
    <div class="crm-container">
      <el-table
        v-loading="loading"
        id="crm-table"
        :row-height="40"
        :data="list"
        :height="tableHeight"
        use-virtual
        highlight-current-row
        class="n-table--border el-table-header--white"
        stripe
        border
        style="width: 100%"
        @row-dblclick="editAttendance">
        <el-table-column
          v-for="(item, index) in noChildrenList"
          :key="index"
          :prop="item.fieldName"
          :label="item.name"
          :min-width="item.width"
          :formatter="fieldFormatter"
          align="center"
          show-overflow-tooltip/>
        <el-table-column
          align="center"
          label="加班费（元）"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <el-button v-if="scope.row.workOvertimePay" type="info" plain size="mini" @click="showClockList(scope.row)">{{ scope.row.workOvertimePay }}</el-button>
            <span v-else>--</span>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, index) in childrenList"
          :key="index+199"
          :label="item.name"
          :min-width="item.width"
          align="center"
          show-overflow-tooltip>
          <el-table-column
            v-for="(child, childIndex) in item.children"
            :key="childIndex+99"
            :prop="child.fieldName"
            :label="child.name"
            :min-width="child.width"
            :formatter="fieldFormatter"
            show-overflow-tooltip/>
        </el-table-column>
        <div slot="empty">
          <p>暂无数据</p>
          <el-button v-if="refreshData.showRefresh" :disabled="refreshData.refreshDisabled" type="primary" size="mini" @click="refreshList">{{ refreshData.refreshText }}</el-button>
          <el-button v-else type="primary" size="mini" @click="generator">点击生成</el-button>
        </div>
      </el-table>
      <div class="p-contianer">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="pageSizes"
          :page-size.sync="pageSize"
          :total="total"
          class="p-bar"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"/>
      </div>
    </div>

    <form-edit-dialog
      ref="formEditDialog"
      :form.sync="formEditForm"
      :fields="formEditFields"
      :visible.sync="formEditDialogShow"
      title="编辑"
      @pass="save"
    />

    <table-clock-dialog
      v-if="tableClockDialogShow"
      ref="tableClockDialog"
      :visible.sync="tableClockDialogShow"
      :employee-id.sync="clockParams.employeeId"
      :year.sync="clockParams.year"
      :month.sync="clockParams.month"
    />
  </div>
</template>

<script>
import {
  hrmDingtalkAttendanceQueryPageListAPI,
  hrmDingtalkAttendanceExportAPI,
  hrmDingtalkAttendanceUpdateAPI,
  hrmDingtalkAttendanceQueryDingtalkDeptsAPI,
  hrmDingtalkAttendanceStaticalGeneratorAPI
} from '@/api/hrm/dingtalkAttendance'


import XrHeader from '@/components/XrHeader'

import moment from 'moment'
import { mapGetters } from 'vuex'
import { isEmpty } from '@/utils/types'
import { downloadExcelWithResData } from '@/utils'


import FormEditDialog from './components/FormEditDialog'
import TableClockDialog from './components/TableClockDialog'
import dingtalkUtil from './model/dingtalk'

export default {
  name: 'DingtalkIndex',
  components: {
    XrHeader,
    FormEditDialog,
    TableClockDialog
  },
  data() {
    const now = new Date()
    return {
      loading: false, // 加载动画
      tableHeight: document.documentElement.clientHeight - 250, // 表的高度
      list: [],
      fieldList: [],
      currentPage: 1,
      pageSize: 15,
      pageSizes: [15, 30, 50],
      total: 0,
      search: '', // 搜索内容
      month: now.getDate() > 2 ? now.getFullYear() + '-' + (now.getMonth() + 1) : now.getFullYear() + '-' + now.getMonth(), // 筛选月份
      pickerOptions: {
        disabledDate: (time) => {
          if (time.getFullYear() > now.getFullYear() && time.getMonth() >= now.getMonth() + 1) {
            return true
          }
        }
      },
      formEditDialogShow: false,
      formEditForm: {},
      formEditFields: [],
      tableClockDialogShow: false,
      deptNameList: [],
      deptName: '',
      clockParams: {
        employeeId: '',
        year: '',
        month: ''
      },
      refreshData: {
        showRefresh: false,
        refreshDisabled: true,
        seconds: 59,
        minute: 4,
        refreshText: '4分59秒后可点击刷新'
      }
    }
  },
  computed: {
    ...mapGetters([
      'hrm'
    ]),

    /** 没有下级表头的表头 */
    noChildrenList() {
      return this.fieldList.filter(item => !item.children || item.children.length == 0)
    },
    /** 有下级表头的表头 */
    childrenList() {
      return this.fieldList.filter(item => item.children && item.children.length > 0)
    }
  },
  created() {
    window.onresize = () => {
      this.tableHeight = document.documentElement.clientHeight - 250
    }
    this.getFieldList()
    this.refreshList()
  },
  methods: {
    /**
     * 搜索
     */
    searchClick(search) {
      this.search = search
      this.refreshList()
    },

    /**
     * 获取表头展示字段
     */
    getFieldList() {
      let month
      if (!this.month) {
        const now = new Date()
        month = now.getMonth()
      } else if (this.month.indexOf('-') != -1) {
        const split = this.month.split('-')
        month = split[1]
      }
      let lastMonth, lastMonth2
      if (month == 1) {
        lastMonth = 12
        lastMonth2 = 11
      } else if (month == 2) {
        lastMonth = month - 1
        lastMonth2 = 12
      } else {
        lastMonth = month - 1
        lastMonth2 = month - 2
      }
      this.fieldList = [
        { fieldName: 'dingtalkDeptName', name: '部门', sortable: '', width: 80 },
        { fieldName: 'name', name: '姓名', sortable: '', width: 80 },
        { fieldName: 'hiredDate', name: '入职时间', sortable: '', width: 90 },
        { fieldName: 'position', name: '职位', sortable: '', width: 80 },
        { fieldName: 'shouldAttendanceDays', name: '应出勤天数', sortable: '', width: 78 },
        { fieldName: 'realAttendanceDays', name: '实际出勤天数', sortable: '', width: 78 },
        { fieldName: 'leaveYear', name: '年假（天）', sortable: '', width: 70 },
        { fieldName: 'workOvertime', name: '加班（天）', sortable: '', width: 80 },
        { fieldName: 'leavePaid', name: '调休（天）', sortable: '', width: 80 },
        { fieldName: 'leaveThing', name: '事假（天）', sortable: '', width: 80 },
        { fieldName: 'lateArrivalTimes', name: '迟到/早退（次）', sortable: '', width: 80 },
        { fieldName: 'lateArrivalMinutes', name: '迟到/早退（分钟）', sortable: '', width: 80 },
        { fieldName: 'lateArrivalDeductions', name: '迟到/早退（扣款）', sortable: '', width: 80 },
        { fieldName: 'lackAttendance', name: '缺卡次数', sortable: '', width: 50 },
        { fieldName: 'lackAttendanceDeductions', name: '缺卡扣款', sortable: '', width: 70 },
        { fieldName: 'perfectAttendanceReward', name: '全勤奖', sortable: '', width: 70 },
        { fieldName: 'workOvertimeHours', name: '加班时长（小时）', sortable: '', width: 73 },
        // { fieldName: 'createTime', name: '统计时间', sortable: '', width: 80 },
        { fieldName: '', name: '备注（存休）', sortable: '', width: 210, children: [
          { fieldName: 'yearVacation', name: '年假', sortable: '', width: 60 },
          { fieldName: 'threeMonthVacation', name: '3月前', sortable: '', width: 60 },
          { fieldName: 'twoMonthVacation', name: Number(lastMonth) + '月', sortable: '', width: 50 },
          { fieldName: 'lastMonthVacation', name: Number(lastMonth2) + '月', sortable: '', width: 50 },
          { fieldName: 'thisMonthVacation', name: Number(month) + '月', sortable: '', width: 50 }
        ] }
      ]
    },

    /**
     * 刷新
     */
    refreshList() {
      this.getFieldList()
      this.handleCurrentChange(1)
      this.getDingtalkDeptsList()
    },

    /**
     * 更改每页展示数量
     */
    handleSizeChange(val) {
      this.pageSize = val
      this.getList()
    },

    /**
     * 更改当前页数
     */
    handleCurrentChange(val) {
      this.currentPage = val
      this.getList()
    },

    /**
     * 列表数据
     */
    getList() {
      this.loading = true
      const params = {
        page: this.currentPage,
        limit: this.pageSize,
        pageType: 1,
        employeeName: this.search,
        month: this.month,
        dingtalkDeptName: this.deptName
      }

      if (!params['month']) {
        const now = new Date()
        params['year'] = now.getFullYear()
        params['month'] = now.getMonth()
      } else if (params['month'].indexOf('-') != -1) {
        const split = params['month'].split('-')
        params['year'] = split[0]
        params['month'] = split[1]
      }

      hrmDingtalkAttendanceQueryPageListAPI(params)
        .then(res => {
          this.list = res.data.list
          this.total = res.data.totalRow
          if (res.data.totalRow && Math.ceil(res.data.totalRow / this.pageSize) < this.currentPage && this.currentPage > 1) {
            this.currentPage = this.currentPage - 1
            this.getList()
          } else {
            this.total = res.data.totalRow
            this.loading = false
          }

          this.$nextTick(() => {
            const warpDom = document.querySelector('.el-table__body-wrapper')
            warpDom.scrollTop = 1
            if (warpDom.scrollLeft != 0) {
              warpDom.scrollLeft = warpDom.scrollLeft - 1
            }
          })
          this.loading = false
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 格式化字段
     */
    fieldFormatter(row, column) {
      if (column.property == 'createTime' || column.property == 'hiredDate') {
        return isEmpty(row[column.property]) ? '--' : moment(row[column.property]).format('Y-M-D')
      } else if (row['dingtalkDeptId'] !== dingtalkUtil.warehouseDeptId && (column.property == 'workOvertimeHours' || column.property == 'workOvertimePay')) {
        return '--'
      } else {
        return isEmpty(row[column.property]) ? '--' : row[column.property] == 0 ? '--' : row[column.property]
      }
    },

    getDingtalkDeptsList() {
      const params = {
        month: this.month
      }

      if (!params['month']) {
        const now = new Date()
        params['year'] = now.getFullYear()
        params['month'] = now.getMonth()
      } else if (params['month'].indexOf('-') != -1) {
        const split = params['month'].split('-')
        params['year'] = split[0]
        params['month'] = split[1]
      }
      hrmDingtalkAttendanceQueryDingtalkDeptsAPI(params).then(res => {
        this.deptNameList = res.data
      }).catch(e => {
        console.log(e)
      })
    },

    /**
     * 头部更多操作
     */
    exportExcel() {
      this.loading = true
      const params = {
        search: this.search,
        month: this.month
      }

      for (var key in this.filterObj) {
        params[key] = this.filterObj[key]
      }

      if (!params['month']) {
        const now = new Date()
        params['year'] = now.getFullYear()
        params['month'] = now.getMonth()
      } else if (params['month'].indexOf('-') != -1) {
        const split = params['month'].split('-')
        params['year'] = split[0]
        params['month'] = split[1]
      }

      hrmDingtalkAttendanceExportAPI(params).then(res => {
        downloadExcelWithResData(res)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 修改记录 */
    editAttendance(row, column, event) {
      this.formEditForm = row
      this.formEditFields = dingtalkUtil.getFields(row)
      this.formEditDialogShow = true
    },
    save() {
      this.$refs.formEditDialog.loading = true
      hrmDingtalkAttendanceUpdateAPI(this.formEditForm).then(res => {
        this.$refs.formEditDialog.loading = false
        this.$message.success('修改成功')
        this.formEditDialogShow = false
        this.handleCurrentChange(1)
      }).catch(e => {
        console.log(e)
        this.$refs.formEditDialog.loading = false
      })
    },
    generator() {
      const split = this.month.split('-')
      const params = {
        year: Number(split[0]),
        month: Number(split[1])
      }
      hrmDingtalkAttendanceStaticalGeneratorAPI(params).then(res => {
        this.$message.success(res.data)
        // 刷新按钮
        this.refreshData.showRefresh = true
        this.refreshData.refreshDisabled = true
        const interval = setInterval(() => {
          this.refreshData.refreshText = this.refreshData.minute + '分' + this.refreshData.seconds + '秒后可点击刷新'
          this.refreshData.seconds--
          if (this.refreshData.seconds <= 0) {
            if (this.refreshData.minute == 0) {
              this.refreshData.refreshDisabled = false
              this.refreshData.refreshText = '点击刷新'
              clearInterval(interval)
              return
            } else {
              this.refreshData.minute--
              this.refreshData.seconds = 59
            }
          }
        }, 1000)
      }).catch(e => {
        console.log(e)
      })
    },
    showClockList(data) {
      this.clockParams.employeeId = data.employeeId
      this.clockParams.year = data.year
      this.clockParams.month = data.month
      this.tableClockDialogShow = true
    }
  }
}
</script>

<style lang="scss" scoped>
.dingtalk-index {
  .xr-header {
    /deep/ .xr-header__ft {
      top: 0;
      line-height: 34px;
    }
  }

  /deep/.xr-table-header {
    border-bottom: 1px solid $xr-border-color-base;
    .xr-table-header__body {
      padding: 0;
    }
  }
  .search-button {
    border: none;

    &.is-select {
      background: $xr-color-primary;
      color: white;
    }
  }

  /deep/ .el-table thead .cell {
    white-space: pre-line;
  }

  /deep/ .el-tabs {
    .el-tabs__header {
      margin-bottom: 0;
    }

    .el-tabs__item {
      color: #42526E;
      font-weight: bold;
    }
  }

  .tab-pane-num {
    background-color: #DFE1E6;
    border-radius: 10px;
    color: #42526E;
    display: inline-block;
    font-size: 12px;
    font-weight: bold;
    height: 18px;
    line-height: 18px;
    padding: 0 6px;
    text-align: center;
    white-space: nowrap;
    border: 1px solid #fff;
  }

  .table-more {
    cursor: pointer;
    &:hover {
      color: $xr-color-primary
    }
  }
  .title {
    text-align: center;
    margin: 20px 0;
    h2 {
      display: inline-block;
      margin-right: 15px;
    }
    a {
      color: royalblue;
      text-decoration: underline;
    }
  }
}
</style>
